package net.jiastudy.web.rest.controller.project;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.baomidou.mybatisplus.plugins.Page;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.jiastudy.biz.project.entity.DeptProject;
import net.jiastudy.biz.project.entity.DeptProjectMember;
import net.jiastudy.biz.project.entity.DeptProjectMoney;
import net.jiastudy.biz.project.entity.DeptProjectWork;
import net.jiastudy.biz.project.entity.MoneyImporter;
import net.jiastudy.biz.project.entity.ProjectImporter;
import net.jiastudy.biz.project.service.DeptProjectService;
import net.jiastudy.biz.targettask.entity.ImportWorkVo;
import net.jiastudy.biz.targettask.service.TargetWorkService;
import net.jiastudy.biz.user.entity.User;
import net.jiastudy.core.base.BaseController;
import net.jiastudy.core.common.validgroup.Create;
import net.jiastudy.core.common.validgroup.Update;
import net.jiastudy.core.exception.NotFoundException;
import net.jiastudy.core.exception.ServiceException;
import net.jiastudy.core.utils.UploadUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dept_project")
@Api(value = "DeptProjectController  部门项目")
public class DeptProjectController extends BaseController {
	@Resource
	private DeptProjectService projectService;

	@Value("${upload.path.base}")
	private String basePath;

	@Resource
	private TargetWorkService targetWorkService;

	@RequestMapping(method = RequestMethod.GET)
	@ApiOperation(value = "分页检索列表", notes = "")
	public Page<DeptProject> page(@RequestParam Map<String, String> conditions,
			@PageableDefault(value = 50, sort = { "id" }) Pageable pageable) {
		Page<DeptProject> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		Sort sort = pageable.getSort();
		return projectService.pageDeptProjects(page, conditions, sort);
	}

	@RequestMapping(path="/for_api/list", method = RequestMethod.GET)
	@ApiOperation(value = "分页检索列表", notes = "")
	public Page<DeptProject> pageForDataboard(@RequestParam Map<String, String> conditions,
								  @PageableDefault(value = 50, sort = { "id" }) Pageable pageable) {
		Page<DeptProject> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		Sort sort = pageable.getSort();
		return projectService.pageDeptProjects(page, conditions, sort);
	}
	
	@RequestMapping(method = RequestMethod.POST)
	@ApiOperation(value = "新增", notes = "")
	public DeptProject create(@Validated({ Create.class }) @RequestBody DeptProject project) {
		User user = this.getCurrentUser();
		if (user.getDeptId() == null) {
			throw new NotFoundException("404", "您不属于任何部门，请先加入部门！");
		}
		project.setCreatedUserId(user.getId());
		project.setDeptId(user.getDeptId());
		return projectService.createProject(project);
	}
	
	@RequestMapping(path = "/{id}", method = RequestMethod.PUT)
	@ApiOperation(value = "编辑")
	public DeptProject edit(@PathVariable @ApiParam(name = "id", required = true) Long id,
			@Validated({ Update.class }) @RequestBody DeptProject project) {
		project.setId(id);
		return projectService.updateProject(project);
	}

	@RequestMapping(path = "/{id}", method = RequestMethod.POST)
	@ApiOperation(value = "删除")
	public Boolean delete(@PathVariable @ApiParam(name = "id", required = true) Long id) {
		return projectService.deleteProject(id);
	}
	
	@RequestMapping(path="/{projectId}/work", method = RequestMethod.POST)
	@ApiOperation(value = "新增工作", notes = "")
	public DeptProjectWork createWork(@PathVariable Long projectId, @Validated({ Create.class }) @RequestBody DeptProjectWork work) {
		work.setProjectId(projectId);
		return projectService.createWork(work);
	}
	
	@RequestMapping(path = "/{projectId}/work/{id}", method = RequestMethod.PUT)
	@ApiOperation(value = "编辑工作")
	public DeptProjectWork editWork(@PathVariable Long projectId, @PathVariable @ApiParam(name = "id", required = true) Long id,
			@Validated({ Update.class }) @RequestBody DeptProjectWork work) {
		work.setId(id);
		return projectService.updateWork(work);
	}

	@RequestMapping(path = "/{projectId}/work/{id}", method = RequestMethod.DELETE)
	@ApiOperation(value = "删除工作")
	public boolean editWork(@PathVariable Long projectId, @PathVariable @ApiParam(name = "id", required = true) Long id) {
		return projectService.deleteWork(id);
	}
	
	@RequestMapping(path="/{projectId}/member", method = RequestMethod.POST)
	@ApiOperation(value = "新增成员", notes = "")
	public DeptProjectMember createMember(@PathVariable Long projectId, @Validated({ Create.class }) @RequestBody DeptProjectMember member) {
		member.setProjectId(projectId);
		return projectService.createMember(member);
	}
	
	@RequestMapping(path = "/{projectId}/member/{id}", method = RequestMethod.PUT)
	@ApiOperation(value = "编辑成员")
	public DeptProjectMember editMember(@PathVariable Long projectId, @PathVariable @ApiParam(name = "id", required = true) Long id,
			@Validated({ Update.class }) @RequestBody DeptProjectMember member) {
		member.setId(id);
		return projectService.updateMember(member);
	}

	@RequestMapping(path = "/{projectId}/member/{id}", method = RequestMethod.DELETE)
	@ApiOperation(value = "删除成员")
	public boolean deleteMember(@PathVariable Long projectId, @PathVariable @ApiParam(name = "id", required = true) Long id) {
		return projectService.deleteMemeber(id);
	}
	
	@RequestMapping(path="/{projectId}/money", method = RequestMethod.POST)
	@ApiOperation(value = "新增金额", notes = "")
	public DeptProjectMoney createMoney(@PathVariable Long projectId, @Validated({ Create.class }) @RequestBody DeptProjectMoney money) {
		money.setProjectId(projectId);
		return projectService.createMoney(money);
	}
	
	@RequestMapping(path = "/{projectId}/money/{id}", method = RequestMethod.PUT)
	@ApiOperation(value = "编辑金额")
	public DeptProjectMoney editMoney(@PathVariable Long projectId, @PathVariable @ApiParam(name = "id", required = true) Long id,
			@Validated({ Update.class }) @RequestBody DeptProjectMoney money) {
		money.setId(id);
		return projectService.updateMoney(money);
	}

	@RequestMapping(path = "/{projectId}/money/{id}", method = RequestMethod.DELETE)
	@ApiOperation(value = "删除金额")
	public boolean editMoney(@PathVariable Long projectId, @PathVariable @ApiParam(name = "id", required = true) Long id) {
		return projectService.deleteMoney(id);
	}
	
	@RequestMapping(path = "/{id}", method = RequestMethod.GET)
	@ApiOperation(value = "获取项目")
	public DeptProject get(@PathVariable Long id) {
		return projectService.getById(id);
	}

	@RequestMapping(path = "/for_api/list/all", method = RequestMethod.GET)
	@ApiOperation(value = "获取所有项目，支持搜索")
	public Map<String, List<DeptProject>> findAll(@RequestParam Map<String, Object> conditions) {
		return projectService.findDeptProjects(conditions);
	}

	@RequestMapping(path = "/my/current_year", method = RequestMethod.GET)
	@ApiOperation(value = "当前用户所在部门本年度所有任务", notes = "")
	public List<ImportWorkVo> findWorks() {
		return targetWorkService.findMyDeptCurrentYearWorks();
	}

	@RequestMapping(path = "/import/project", method = RequestMethod.POST)
	@ApiOperation(value = "导入报表")
	public boolean importUser(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty() || file.getSize() == 0) {
			return true;
		}
		Date now = new Date();
		String fileName = file.getOriginalFilename();
		fileName = "/" + now.getTime() + fileName;

		String filePath = UploadUtil.TEMP_PATH + UploadUtil.makeFileDir(now);
		boolean bool = UploadUtil.mkdirs(basePath + filePath);
		if (!bool) {
			logger.error("创建目录失败，请检查权限");
			throw new ServiceException("500", "创建目录失败，请检查权限");
		}
		java.io.File dest = new java.io.File(basePath + filePath + fileName);
		try {
			file.transferTo(dest);
		} catch (IllegalStateException | IOException e) {
			logger.error("文件上传出错了：", e);
		}

		ImportParams params = new ImportParams();
		params.setHeadRows(1);
		params.setTitleRows(1);
		ExcelImportResult<ProjectImporter> list = ExcelImportUtil.importExcelMore(
				dest, ProjectImporter.class, params);

		ImportParams moneyParams = new ImportParams();
		moneyParams.setHeadRows(1);
		moneyParams.setStartSheetIndex(1);
		ExcelImportResult<MoneyImporter> moneyList = ExcelImportUtil.importExcelMore(
				dest, MoneyImporter.class, moneyParams);
		projectService.importProject(list.getList(), moneyList.getList());

		return true;
	}
}
